package cn.walls1717.juc.cas;

import lombok.extern.slf4j.Slf4j;

import java.util.concurrent.CountDownLatch;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * 原子基本数据类型测试
 *
 * @author walls1717
 * @create 2022/12/12 15:48
 **/
@Slf4j
public class AtomicIntegerDemo {

    public static void main(String[] args) throws InterruptedException {
        MyNumber myNumber = new MyNumber();
        CountDownLatch countDownLatch = new CountDownLatch(50);
        for (int i = 1; i <= 50; i++) {
            new Thread(()->{
                try {
                    for (int j = 1; j <= 1000; j++) {
                        myNumber.numAdd();
                    }
                } finally {
                    countDownLatch.countDown();
                }
            }).start();
        }

        // TimeUnit.SECONDS.sleep(2);
        countDownLatch.await();

        int result = myNumber.atomicInteger.get();
        log.info("最终结果 " + result);
    }

}

class MyNumber {
    AtomicInteger atomicInteger = new AtomicInteger(0);

    public void numAdd() {
        atomicInteger.getAndIncrement();
    }
}
